package com.edu.atams.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.metadata.Sheet;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.edu.atams.common.dto.SexNumDto;
import com.edu.atams.common.lang.Result;
import com.edu.atams.common.sheet.StudentUpLoad;
import com.edu.atams.entity.*;
import com.edu.atams.entity.Class;
import com.edu.atams.excel.ExcelListener;
import com.edu.atams.mapper.StudentMapper;
import com.edu.atams.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.edu.atams.utils.ConvertClassUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author czj666
 * @since 2021-10-09
 */
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {
    @Autowired
    ClassService classService;

    @Autowired
    GradeService gradeService;

    @Autowired
    StudentClassService studentClassService;

    @Autowired
    SysUserService sysUserService;

    @Autowired
    StudentMapper studentMapper;

    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;

    @Override
    public String getStudentNo(Student student) {
        Class aClass = classService.getOne(new QueryWrapper<Class>().eq("id", student.getClassId()));
        Grade grade = gradeService.getOne(new QueryWrapper<Grade>().eq("id", aClass.getGradeId()));
        String schoolno = String.valueOf(grade.getYear()) + aClass.getCode() + student.getSchoolno();
        return schoolno;
    }

    @Override
    public Result excelImport(Integer classId, Integer startNum, MultipartFile excel) throws IOException {
        String filename = excel.getOriginalFilename();
        // 对其上传的文件后缀进行判断是否为excel,其实还得判断类型和大小
        if (StrUtil.endWithIgnoreCase(filename,".xlsx") || StrUtil.endWithIgnoreCase(filename,".xls") ){
            InputStream inputStream = new BufferedInputStream(excel.getInputStream());
            ExcelListener excelListener = new ExcelListener();
            // 实例化ExcelReader,传入输入流和监听器，将其读取的每一条数据进行监听拦截处理,
            // 因为read方法读取之后，返回值为void没有任何操作，只负责读每一条数据，并转为指定类型，所以才用到监听器进行对每条数据进行保存
            ExcelReader excelReader = new ExcelReader(inputStream, null, excelListener);
            // 进去读取输入流对应的表，每读取一条数据，映射封装好，每一条数据都会跳到监听器的invoke方法进行处理
            excelReader.read(new Sheet(1,1, StudentUpLoad.class));
            List<StudentUpLoad> data = ConvertClassUtil.castList(excelListener.getData(), StudentUpLoad.class);

            return this.saveExcelData(classId, startNum, data);
        } else{
            return Result.fail("不支持文件格式xls或者xlsx以外的格式");
        }
    }

    //获取全部学生的人数
    @Override
    public Integer getAllNum() {
        List<Student> list = this.list();
        return list.size();
    }

    //获取男女性别人数
    @Override
    public List<SexNumDto> getSexNum() {
        return studentMapper.getSexNum();
    }

    public Result saveExcelData(Integer classId,Integer startNum,List<StudentUpLoad> data){
//        int studentNum = 0;
        for (StudentUpLoad studentUpLoad : data) {
//            studentNum++;
            //存入学生的资料
            Student student = new Student();
            student.setName(studentUpLoad.getName());
            student.setIdCard(studentUpLoad.getIdCard());
            if (studentUpLoad.getSex().equals("男")){
                student.setSex(1);
            }else if (studentUpLoad.getSex().equals("女")){
                student.setSex(2);
            }else {
                return Result.fail("性别有误");
            }
            this.save(student);
            //存入学生-班级
            StudentClass studentClass = new StudentClass();
            studentClass.setStudentId(student.getId());
            studentClass.setClassId(classId);
            studentClassService.save(studentClass);
            //生成学号
            String studentIdNum = null;
            if (startNum < 10){
                studentIdNum = "0" + String.valueOf(startNum);
            }else {
                studentIdNum = String.valueOf(startNum);
            }
            Class classByStudentId = this.getClassByStudentId(student.getId());
            studentIdNum = String.valueOf(classByStudentId.getGrade().getYear()) + classByStudentId.getGrade().getCode() + classByStudentId.getCode() + studentIdNum;
            student.setSchoolno(studentIdNum);
            this.updateById(student);
            //生成账号
            Integer userid = this.setSysUser(student.getSchoolno());
            student.setUserId(userid);
            this.updateById(student);
            startNum++;
        }
        return Result.succ("");

    }


    //根据学号生成账号并范围SysUserId
    public Integer setSysUser(String schoolno){
        SysUser sysUser = new SysUser();
        sysUser.setRoleType(1);
        sysUser.setUsername(schoolno);
        String password = bCryptPasswordEncoder.encode("123456");
        sysUser.setPassword(password);
        sysUserService.save(sysUser);
        return sysUser.getId();
    }

    //根据学生表Id查找对应的班级信息
    public Class getClassByStudentId(Integer id){
        StudentClass studentClass = studentClassService.getOne(new QueryWrapper<StudentClass>().eq("student_id", id));
        Class aClass = classService.getOne(new QueryWrapper<Class>().eq("id", studentClass.getClassId()));
        Grade grade = gradeService.getOne(new QueryWrapper<Grade>().eq("id", aClass.getGradeId()));
        aClass.setGrade(grade);
        return aClass;
    }

}
